package com.api.qfengx.config;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.weaver.qfengx.DaoUtils;
import com.weaver.qfengx.LogUtils;
import com.weaver.qfengx.StringUtils;
import com.weaver.qfengx.WorkflowUtils;
import com.weaver.qfengx.annotation.QfOperationLog;
import com.weaver.qfengx.annotation.QfTransaction;
import com.weaver.qfengx.config.DevModeConfig;
import com.weaver.qfengx.config.PropConfig;
import com.weaver.qfengx.entity.Result;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.Map;

@Path("/qfengx/config")
public class ConfigApi {

    @GET
    @Path("/load")
    @Produces(MediaType.APPLICATION_JSON)
    @QfOperationLog("uf_operation_log") // 拦截记录整个方法的日志内容到指定表中
    @QfTransaction // 异常事务处理
    public String load(@Context HttpServletRequest request,
                       @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        if (user.getUID() != 1) {
            return JSON.toJSONString(Result.noPermission());
        }
        String tableName = request.getParameter("tablename");
        if (StringUtils.isNotEmpty(tableName)) {
            DevModeConfig.setConfigTableName(tableName);
        }
        List<PropConfig> oldList = DevModeConfig.getConfigList();
        DevModeConfig.loadConfig();
        LogUtils.refreshLevel();
        DaoUtils.refreshConfig();
        Map<String, Object> res = Maps.newHashMap();
        res.put("current", DevModeConfig.getConfigList());
        res.put("old", oldList);
        return JSON.toJSONString(Result.ok(res));
    }

    @GET
    @Path("/archiving")
    @Produces(MediaType.APPLICATION_JSON)
    public String archiving(@Context HttpServletRequest request,
                            @Context HttpServletResponse response) {
        String rid = request.getParameter("rid");
        if (StringUtils.isEmpty(rid)) {
            return JSON.toJSONString(Result.paramErr());
        }
        User user = HrmUserVarify.getUser(request, response);
        if (user.getUID() != 1) {
            return JSON.toJSONString(Result.noPermission());
        }
        boolean res = WorkflowUtils.archiving(rid);
        return JSON.toJSONString(Result.ok(res));
    }

}
